#!/bin/sh

### BEGIN INIT INFO
# Provides:          ${SERVICE_NAME}
# Required-Start:    $network
# Required-Stop:     $network
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
# Short-Description: Start ${SERVICE_NAME} daemon.
# Description:       Start ${SERVICE_NAME} daemon.
### END INIT INFO

# SERVICE_NAME=demo
# SERVICE_PATH=/usr/bin/demo
# SERVICE_PARAM="-c /etc/demo.conf"
# SERVICE_HOME=/home/user1
# SERVICE_USER=user1
SERVICE_PID_FILE=/var/run/${SERVICE_NAME}.pid

start() {
    start-stop-daemon --start \
    --chdir  "${SERVICE_HOME}" \
    --chuid "${SERVICE_USER}" \
    --user "${SERVICE_USER}" \
    --background \
    --make-pidfile --pidfile "${SERVICE_PID_FILE}" \
    --exec ${SERVICE_PATH} -- ${SERVICE_PARAM}
}

stop() {
    start-stop-daemon --stop \
    --chdir "${SERVICE_HOME}" \
    --chuid "${SERVICE_USER}" \
    --user "${SERVICE_USER}" \
    --pidfile "${SERVICE_PID_FILE}"
}

restart() {
    stop
    start
}

reload() {
    start-stop-daemon --stop \
    --chdir "${SERVICE_HOME}" \
    --chuid "${SERVICE_USER}" \
    --user "${SERVICE_USER}" \
    --signal HUP \
    --pidfile "${SERVICE_PID_FILE}"
}

status() {
    start-stop-daemon --status \
    --chdir "${SERVICE_HOME}" \
    --chuid "${SERVICE_USER}" \
    --user "${SERVICE_USER}" \
    --pidfile "${SERVICE_PID_FILE}"
    
    case $? in
        0)
           echo "$SERVICE_NAME is running."
           ;;
        *)
           echo "$SERVICE_NAME is stopped."
           ;;
    esac
}

case $1 in
    start)
       start
       ;;
    stop)
       stop
       ;;
    restart)
       restart
       ;;
    reload)
       reload
       ;;
    status)
       status
       ;;
    *)
       echo "Usage: $0 {start|stop|restart|reload|status}"
       ;;
esac

exit 0